package com.qzl.feiq.protocol;


import cn.hutool.system.SystemUtil;
import com.qzl.feiq.enu.MessageTypeEnum;
import com.qzl.feiq.message.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageCodec;
import lombok.extern.slf4j.Slf4j;
import com.qzl.feiq.config.StaticConfig;
import com.qzl.feiq.util.FeiQUtils;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Objects;

@Slf4j
/**
 * 飞鸽定义的通信协议
 * Ver(1): PacketNo:SenderName:SenderHost:CommandNo:AdditionalSection
 * 版本号（现在是1）:数据包编号:登录名:主机名:命令:用户名
 */
public class UdpMessageCodec extends MessageToMessageCodec<ByteBuf, Message> {
    @Override
    public void encode(ChannelHandlerContext ctx, Message msg, List<Object> outList) throws Exception {
        ByteBuf out = ctx.alloc().buffer();
        String username = /*StringUtils.isNotBlank(msg.getSenderName()) ? msg.getSenderName() : */SystemUtil.getHostInfo().getName();
        String hostname = /*StringUtils.isNotBlank(msg.getSenderHost()) ? msg.getSenderHost() :*/ System.getProperty("os.name");
        String sb = StaticConfig.VERSION +
                StaticConfig.SEPARATOR +
                FeiQUtils.getPacketNo() +
                StaticConfig.SEPARATOR +
                username +
                StaticConfig.SEPARATOR +
                hostname +
                StaticConfig.SEPARATOR +
                msg.getCommand() +
                StaticConfig.SEPARATOR;
        if (Objects.equals(MessageTypeEnum.broadcast.getType(), msg.getMessageType().getType())){
            sb += username;
        } else if (Objects.equals(MessageTypeEnum.message.getType(), msg.getMessageType().getType())){
            sb += msg.getMsg();
        }
        if (!msg.getToUserIp().contains("255")){
            log.info("upd发出的消息：{}, 接收者ip:{}", sb, msg.getToUserIp());
        }
        out.writeBytes(sb.getBytes(StaticConfig.CHARSET));
        outList.add(new DatagramPacket(out, new InetSocketAddress(msg.getToUserIp(), StaticConfig.UDP_PORT)));
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        log.info("收到的字节数：{}", in.readableBytes());
        String baseMsg = in.toString(StaticConfig.CHARSET);
        log.info("upd收到的消息：{}", baseMsg);
    }

}
